package ylyhappy.cn.ideavim.lg.db

import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase

/**
 * input array of line_id, comment, name
 * create simple config
 */
fun newConfig(db: SQLiteDatabase, line_ids: Array<Long>?, comment: String, name: String) {
    db.beginTransaction()
    try {
        // create config record and get configId
        val values = ContentValues().apply {
            put("comment", comment)
            put("name", name)
        }
        val configId = db.insertOrThrow("Config", null, values)

        // create config_and_lines
        line_ids?.forEach { line_id ->
            run {
                db.execSQL("INSERT INTO ConfigAndLine(config_id, line_id) VALUES(\"$configId\", \"$line_id\")")
            }
        }
        db.setTransactionSuccessful()
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        db.endTransaction()
    }
}

/**
 * delete config by id
 */
fun deleteConfigByIds(db: SQLiteDatabase, ids: Array<Int>) {
    try {
        db.beginTransaction()
        ids.forEach { e ->
            run {
                db.execSQL("DELETE FROM Config WHERE id = $e")
            }
        }
        db.setTransactionSuccessful()
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        db.endTransaction()
    }
}

/**
 * create default data offer user
 */
fun createDefaultConfig(db: SQLiteDatabase) {
    newConfig(db, arrayOf(0, 1, 2), "defualt_config", "default_config")
}

fun deleteConfigAndLineByIds(db: SQLiteDatabase, ids: Array<Int>) {
    try {
        db.beginTransaction()
        ids.forEach { e ->
            run {
                db.execSQL("DELETE FROM ConfigAndLine WHERE id = $e")
            }
        }
        db.setTransactionSuccessful()
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        db.endTransaction()
    }
}

fun selectConfigById(db:SQLiteDatabase, ConfigId: Int){
    db.execSQL("")
}